<template>
  <div class="chat-page">
    <!-- 左侧好友列表 -->
    <div class="sidebar">
      <!-- 返回按钮 + 标题 -->
      <div class="sidebar-header">
        <div 
          class="back-btn" 
          @click="handleBack"
        ></div>
        <h2 class="sidebar-title">好友</h2>
      </div>

      <!-- 搜索框 -->
      <el-input 
        v-model="searchKeyword" 
        placeholder="搜索好友" 
        class="search-input"
        clearable
      />

      <!-- 好友列表 -->
      <el-menu 
        class="friend-list" 
        :default-active="activeFriendId"
        @select="handleFriendSelect"
      >
        <el-menu-item 
          v-for="friend in filteredFriends" 
          :key="friend.id" 
          :index="friend.id + ''"
        >
          <el-avatar 
            :src="friend.avatar" 
            class="friend-avatar"
          />
          <span class="friend-nickname">{{ friend.nickname }}</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 右侧聊天区 -->
    <div class="chat-section" v-if="activeFriend">
      <!-- 聊天顶部信息 -->
      <div class="chat-header">
        <el-avatar 
          :src="activeFriend.avatar" 
          class="chat-header-avatar"
        />
        <div class="chat-header-info">
          <h3 class="chat-header-nickname">
            {{ activeFriend.nickname }}
            <span class="online-status" v-if="activeFriend.isOnline">
              🔥 {{ activeFriend.onlineDuration }}前在线
            </span>
          </h3>
          <div class="chat-header-actions">
            <el-button 
              type="text" 
              @click="handleExitSession"
            >退出会话</el-button>
            <el-dropdown>
              <el-button type="text">
                ... <i class="el-icon-arrow-down"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>设置聊天背景</el-dropdown-item>
                  <el-dropdown-item>清空聊天记录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>

      <!-- 聊天内容区 -->
      <div class="chat-content">
        <!-- 系统提示（如点赞、分享） -->
        <div class="system-message" v-if="chatMessages.length === 0">
          点击左侧好友开始聊天吧～
        </div>
        <div 
          v-for="(msg, index) in chatMessages" 
          :key="index" 
          class="message-item"
          :class="{ 
            'self-message': msg.isSelf, 
            'other-message': !msg.isSelf 
          }"
        >
          <div class="message-avatar" v-if="!msg.isSelf">
            <el-avatar :src="activeFriend.avatar" />
          </div>
          <div class="message-bubble">
            <div class="message-content" :style="{ background: msg.isSelf ? '#409EFF' : '#2f3237' }">
              {{ msg.content }}
            </div>
            <div class="message-time">{{ formatTime(msg.time) }}</div>
          </div>
          <div class="message-avatar" v-if="msg.isSelf">
            <el-avatar :src="userAvatar" />
          </div>
        </div>
      </div>

      <!-- 输入区 -->
      <div class="chat-footer">
        <el-input 
          v-model="inputValue" 
          class="chat-input" 
          placeholder="发送消息" 
          clearable
          @keyup.enter="sendMessage"
        >
          <template #append>
            <el-button 
              icon="el-icon-send" 
              @click="sendMessage"
            ></el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script>
import { friend } from '@/utils/api'
import { ElMessageBox } from 'element-plus'
import { computed, onMounted, ref } from 'vue'

export default {
  name: 'Chat',
  setup() {
    // 好友列表数据
    const friends = ref([])
    const activeFriendId = ref('')
    const searchKeyword = ref('')
    const inputValue = ref('')
    const userAvatar = '/default-avatar.png'

    // 获取好友列表
    const fetchFriends = async () => {
      const res = await friend.getList()
      friends.value = (res.data || res).map(f => {
        const u = f.user1 && f.user1._id !== undefined && f.user1._id !== f.user2._id ? f.user2 : f.user1
        return {
          id: u._id,
          nickname: u.nickname || '好友',
          avatar: u.avatar || '/default-avatar.png',
          isOnline: false,
          onlineDuration: '',
          messages: []
        }
      })
      if (friends.value.length > 0) activeFriendId.value = friends.value[0].id + ''
    }

    onMounted(fetchFriends)

    // 计算当前激活的好友
    const activeFriend = computed(() => {
      return friends.value.find(f => f.id === Number(activeFriendId.value))
    })

    // 计算过滤后的好友列表
    const filteredFriends = computed(() => {
      return friends.value.filter(friend => 
        friend.nickname.includes(searchKeyword.value)
      )
    })

    // 计算聊天消息（合并系统消息 + 用户消息）
    const chatMessages = computed(() => {
      if (!activeFriend.value) return []
      return activeFriend.value.messages.map(msg => ({
        ...msg,
        time: formatTime(msg.time)
      }))
    })

    // 切换好友
    const handleFriendSelect = (key) => {
      activeFriendId.value = key
    }

    // 返回按钮
    const handleBack = () => {
      // 可跳转回上一级页面（如消息列表）
      window.history.back()
    }

    // 退出会话
    const handleExitSession = () => {
      ElMessageBox.confirm(
        '确定要退出会话吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 可实现退出逻辑（如清空聊天、跳转）
        activeFriendId.value = ''
      }).catch(() => {})
    }

    // 发送消息
    const sendMessage = () => {
      if (!inputValue.value.trim()) return
      if (!activeFriend.value) return

      // 构造消息
      const newMsg = {
        content: inputValue.value,
        time: new Date(),
        isSelf: true
      }

      // 更新聊天记录
      activeFriend.value.messages.push(newMsg)
      inputValue.value = ''

      // 模拟对方回复（演示用）
      setTimeout(() => {
        activeFriend.value.messages.push({
          content: '收到你的消息啦～',
          time: new Date(),
          isSelf: false
        })
      }, 1000)
    }

    // 格式化时间
    const formatTime = (time) => {
      if (time instanceof Date) {
        const hour = time.getHours().toString().padStart(2, '0')
        const min = time.getMinutes().toString().padStart(2, '0')
        return `${hour}:${min}`
      }
      return time
    }

    return {
      userAvatar,
      friends,
      activeFriendId,
      searchKeyword,
      inputValue,
      activeFriend,
      filteredFriends,
      chatMessages,
      handleFriendSelect,
      handleBack,
      handleExitSession,
      sendMessage,
      formatTime
    }
  }
}
</script>

<style scoped>
.chat-page {
  display: flex;
  height: 100vh;
  background-color: #ffffff;
  color: #fff;
}

/* 左侧 sidebar */
.sidebar {
  width: 260px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #050505;
}

.sidebar-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #3c3f47;
}

/* 自定义返回按钮 */
.back-btn {
  width: 20px;
  height: 20px;
  border-left: 2px solid #000000;
  border-bottom: 2px solid #000000;
  transform: rotate(45deg);
  cursor: pointer;
  margin-right: 10px;
  transition: all 0.3s ease;
}
.back-btn:hover {
  border-color: #409eff;
}

.sidebar-title {
  color: #000000;
  font-size: 18px;
  font-weight: bold;
}

.search-input {
  background-color: #9b9c9e;
  border: none;
  color: #d2d1d1;
}
.search-input::placeholder {
  color: #aaa;
}

.friend-list {
  flex: 1;
  background-color: transparent;
  border: none;
}
.el-menu-item {
  color: #fff;
  display: flex;
  align-items: center;
  padding: 12px 20px;
}
.friend-avatar {
  width: 36px;
  height: 36px;
  margin-right: 10px;
}
.friend-nickname {
  font-size: 14px;
}

/* 右侧聊天区 */
.chat-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 聊天顶部 */
.chat-header {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  background-color: #2b2d33;
  border-bottom: 1px solid #3c3f47;
}
.chat-header-avatar {
  width: 48px;
  height: 48px;
  margin-right: 12px;
}
.chat-header-info {
  display: flex;
  flex-direction: column;
}
.chat-header-nickname {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 4px;
}
.online-status {
  font-size: 12px;
  color: #ff6b6b;
  margin-left: 8px;
}
.chat-header-actions {
  display: flex;
  gap: 16px;
  margin-top: 4px;
}

/* 聊天内容区 */
.chat-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.system-message {
  text-align: center;
  color: #aaa;
  margin-top: 20px;
}
.message-item {
  display: flex;
  align-items: flex-start;
}
.self-message {
  justify-content: flex-end;
}
.other-message {
  justify-content: flex-start;
}
.message-avatar .el-avatar {
  width: 36px;
  height: 36px;
  margin: 0 10px;
}
.message-bubble {
  display: flex;
  flex-direction: column;
  max-width: 60%;
}
.message-content {
  padding: 8px 12px;
  border-radius: 6px;
  word-wrap: break-word;
}
.message-time {
  font-size: 12px;
  color: #aaa;
  margin-top: 4px;
  align-self: flex-end;
}

/* 输入区 */
.chat-footer {
  padding: 12px 20px;
  background-color: #2b2d33;
  border-top: 1px solid #3c3f47;
}
.chat-input {
  background-color: #3c3f47;
  border: none;
  color: #fff;
}
.chat-input::placeholder {
  color: #aaa;
}
.el-input__append .el-button {
  color: #409eff;
}
</style>